package com.ruoyi.system.controller;

import java.util.*;
import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.job.TaskException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.tools.UserSigTool;
import com.ruoyi.web.controller.entity.ConnectCallbackReqVO;
import lombok.extern.slf4j.Slf4j;
import org.quartz.SchedulerException;
import org.springframework.boot.CommandLineRunner;
import org.springframework.data.redis.connection.RedisServer;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.DwPhoneConnect;
import com.ruoyi.system.service.IDwPhoneConnectService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.client.RestTemplate;

/**
 * 呼叫管理Controller
 * 
 * @author ruoyi
 * @date 2024-02-05
 */
@RestController
@Slf4j
@RequestMapping("/call/connect")
public class DwPhoneConnectController extends BaseController implements CommandLineRunner
{
    @Autowired
    private IDwPhoneConnectService dwPhoneConnectService;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private TokenService tokenService;

    /**
     * 查询呼叫管理列表
     */
    @PreAuthorize("@ss.hasPermi('call:connect:list')")
    @GetMapping("/list")
    public TableDataInfo list(DwPhoneConnect dwPhoneConnect)
    {
        startPage();
        List<DwPhoneConnect> list = dwPhoneConnectService.selectDwPhoneConnectList(dwPhoneConnect);
        return getDataTable(list);
    }

    /**
     * 呼叫我的列表
     */
    @PreAuthorize("@ss.hasPermi('call:connect:list')")
    @GetMapping("/callMe/list")
    public TableDataInfo callMeList(DwPhoneConnect dwPhoneConnect)
    {
        dwPhoneConnect.setCalledUserId(getUserId());
        startPage();
        List<DwPhoneConnect> list = dwPhoneConnectService.selectDwPhoneConnectList(dwPhoneConnect);
        return getDataTable(list);
    }

    /**
     * 我的呼叫列表
     */
    @PreAuthorize("@ss.hasPermi('call:connect:list')")
    @GetMapping("/mycall/list")
    public TableDataInfo myCallList(DwPhoneConnect dwPhoneConnect)
    {
        dwPhoneConnect.setCallUserId(getUserId());
        startPage();
        List<DwPhoneConnect> list = dwPhoneConnectService.selectDwPhoneConnectList(dwPhoneConnect);
        return getDataTable(list);
    }

    /**
     * 导出呼叫管理列表
     */
    @PreAuthorize("@ss.hasPermi('call:connect:export')")
    @Log(title = "呼叫管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, DwPhoneConnect dwPhoneConnect)
    {
        List<DwPhoneConnect> list = dwPhoneConnectService.selectDwPhoneConnectList(dwPhoneConnect);
        ExcelUtil<DwPhoneConnect> util = new ExcelUtil<DwPhoneConnect>(DwPhoneConnect.class);
        util.exportExcel(response, list, "呼叫管理数据");
    }

    /**
     * 获取呼叫管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('call:connect:query')")
    @GetMapping(value = "/{connectId}")
    public AjaxResult getInfo(@PathVariable("connectId") Long connectId)
    {
        return success(dwPhoneConnectService.selectDwPhoneConnectByConnectId(connectId));
    }

    /**
     * 新增呼叫管理
     */
    @PreAuthorize("@ss.hasPermi('call:connect:add')")
    @Log(title = "呼叫管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody DwPhoneConnect dwPhoneConnect)
    {
        return toAjax(dwPhoneConnectService.insertDwPhoneConnect(dwPhoneConnect));
    }

    /**
     * 修改呼叫管理
     */
    @PreAuthorize("@ss.hasPermi('call:connect:edit')")
    @Log(title = "呼叫管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody DwPhoneConnect dwPhoneConnect)
    {
        return toAjax(dwPhoneConnectService.updateDwPhoneConnect(dwPhoneConnect));
    }

    /**
     * 删除呼叫管理
     */
    @PreAuthorize("@ss.hasPermi('call:connect:remove')")
    @Log(title = "呼叫管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{connectIds}")
    public AjaxResult remove(@PathVariable Long[] connectIds)
    {
        return toAjax(dwPhoneConnectService.deleteDwPhoneConnectByConnectIds(connectIds));
    }

    @Anonymous
    @PostMapping("/callback")
    public JSONObject call(@RequestBody JSONObject jsonObject, HttpServletRequest request)
    {
        ConnectCallbackReqVO requestVO = new ConnectCallbackReqVO(jsonObject);
        log.info(requestVO.toString());
        Map map = new HashMap();
        Enumeration paramNames = request.getParameterNames();
        while (paramNames.hasMoreElements()) {
            String paramName = (String) paramNames.nextElement();
            String[] paramValues = request.getParameterValues(paramName);
            if (paramValues.length == 1) {
                String paramValue = paramValues[0];
                if (paramValue.length() != 0) {
                    map.put(paramName, paramValue);
                }
            }
        }

        DwPhoneConnect dwPhoneConnect = new DwPhoneConnect();
        dwPhoneConnect.setCallStatus(requestVO.getCallStatus());
        if (requestVO.getRole().equals("caller")){
            dwPhoneConnect.setCallUserId(Long.parseLong(requestVO.getUserId()));
        }else {
            dwPhoneConnect.setCalledUserId(Long.parseLong(requestVO.getUserId()));
        }
        dwPhoneConnect.setCallId(requestVO.getCallId());
        dwPhoneConnect.setConnectTime(requestVO.getCallStatus().equals("0")? requestVO.getEndTs() - requestVO.getAcceptTs() : 0L);
        dwPhoneConnect.setCreateTime(new Date(requestVO.getEventTime()));
        dwPhoneConnect.setEventType(requestVO.getCallType().equals("single")?"0":"1");
        dwPhoneConnectService.insertDwPhoneConnect(dwPhoneConnect);

        JSONObject returnJson = new JSONObject();
        returnJson.put("ErrorMessage","OK");
        returnJson.put("ErrorCode",0);
        return returnJson;
    }

    @Override
    public void run(String... args) {
        String userSig = UserSigTool.getUserSig("administrator", tokenService.getExpireTime());
        Random random = new Random();
        // 生成随机的64位长整型数字
        long unsignedInt = (random.nextLong() & Long.MAX_VALUE);
        String url = "https://callkit.trtc.tencent-cloud.com/v1/callback/set?sdkappid="+ RuoYiConfig.getSdkAppId() +"&identifier=administrator&usersig=" + userSig + "&random=" +String.valueOf(unsignedInt)+ "&contenttype=json";
        JSONObject json = new JSONObject();
        List<String> list = new ArrayList<>();
        list.add("not_answer");
        list.add("cancel");
        list.add("normal_end");
        list.add("reject");
        json.put("address","http://47.94.38.170:8090/call/connect/callback");
        json.put("actions", list);
        JSONObject result = restTemplate.postForObject(url, json, JSONObject.class);
        log.info("状态码:{}，回调地址:{}" , result.getInteger("errorCode"), result.getString("data") );
    }
}
